//
//  HYFileDownloadModel.m
//  XPlayer
//
//  Created by liguoqing on 2023/10/12.
//

#import "HYFileDownloadModel.h"

@implementation HYFileDownloadModel

+ (NSDictionary *)JSONKeyPathsByPropertyKey{
    return nil;
}

#pragma mark - LKDBHelper

+ (NSString *)getTableName{
    return @"DOWNLOAD";
}

+ (NSString *)getPrimaryKey{
    return @"_id";
}

#pragma mark - DB Mapping

//! 数据库字段映射，key为数据库字段，value为属性
+ (NSDictionary *)tableMapping{
    return @{
        @"_id": @"_id",
        @"fileName":@"fileName",
        @"fileUrl":@"fileUrl",
        @"fileSize":@"fileSize",
        @"fileType":@"fileType",
        @"imageName":@"imageName",
        @"progress":@"progress",
        @"downloadStatus":@"downloadStatus",
        @"createDate":@"createDate",
        @"downloadDate":@"downloadDate",
        @"folderIdentification":@"folderIdentification",
        @"isPrivate":@"isPrivate"
    };
}

- (instancetype)initWithVideoModel:(HYVideoModel *)videoModel
                         isPrivate:(BOOL)isPrivate
              folderIdentification:(NSString *)folderIdentification
{
    self = [super init];
    if(self){
        self.fileName = videoModel.videoTitle;
        self.fileUrl = videoModel.videoUrl;
        self.fileType = videoModel.isAudio?1:0;
        self.fileSize = videoModel.videoSize;
        self.imageName = videoModel.videoImagePath;
        self.progress = 0;
        self.downloadStatus = 0;
        self.createDate = videoModel.createDate;
        self.downloadDate = [CommUtls encodeTimeYearMonthDay:[NSDate date]];
        self.folderIdentification = folderIdentification;
        self.isPrivate = videoModel.isPrivate?:self.isPrivate;
    }
    return self;
}

+ (NSArray *)fetchAllDownloadTaskData
{
    NSString *sql = @"select *from DOWNLOAD where 1 order by downloadDate DESC";
    return [[self fetchDownloadTaskWhere:sql] copy];
}

+ (NSArray *)fetchDownloadTaskWhere:(NSString *)where
{
    return [[self searchWithSQL:where] copy];
}

+ (void)updateDownloadFileName:(NSString *)fileName fileUrl:(NSString *)fileUrl
{
    NSString *sql = [NSString stringWithFormat:@"select *from DOWNLOAD where fileUrl = '%@'",fileUrl];
    HYFileDownloadModel *model = [self fetchDownloadTaskWhere:sql].firstObject;
    if(model){
        model.fileName = fileName;
        [model updateToDB];
    }
}

+ (void)clearAllData
{
    [self deleteWithWhere:@"1"];
}

@end
